const path = require('path');
const glob = require('glob');

const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const FriendlyErrorsWebpackPlugin = require('friendly-errors-webpack-plugin');

// 多页页面应用
const setMAP = () => {
	const entry = {};
	const HtmlWebpackPlugins = [];
	const entryFiles = glob.sync(path.join(__dirname, './src/*/*.js'));
	Object.keys(entryFiles).map((index) => {
		const entryFile = entryFiles[index];
		const match = entryFile.match(/src\/(.*)\/index\.js/);
		const pageName = match && match[1];
		entry[pageName] = entryFile;
		return HtmlWebpackPlugins.push(
			new HtmlWebpackPlugin({
				title: 'search',
				template: path.resolve(__dirname, `src/${pageName}/index.template.html`),
				hash: false,
				filename: `${pageName}.html`,
				inject: true,
				// chunks: ['vendors',pageName],
				chunks: [pageName],
				minify: {
					html5: true,
					collapseWhitespace: true,
					preserveLineBreaks: true,
					minifyCSS: true,
					minifyJS: true,
					removeComments: true,
					removeAttributeQuotes: true,
				},
			}),
		);
	});

	return {
		entry,
		HtmlWebpackPlugins,
	};
};

const { entry, HtmlWebpackPlugins } = setMAP();

module.exports = {
	entry,
	module: {
		rules: [
			{
				test: /.js$/,
				use: ['babel-loader', 'eslint-loader'],
			},
			{
				test: /.css$/,
				use: [MiniCssExtractPlugin.loader, 'css-loader', 'postcss-loader'],
			},
			{
				test: /.less$/,
				use: [
					MiniCssExtractPlugin.loader,
					'css-loader',
					'less-loader',
					'postcss-loader',
					{ // px 转rem
						loader: 'px2rem-loader',
						options: {
							remUni: 75, // 是以750的设计稿设计的  1rem => 75px
							remPrecision: 8, // px转换成rem的小数点的位数
						},
					},
				],
			},
			{
				test: /\.(png|svg|kpg|gif|jpeg|jpg)$/,
				use: [{
					loader: 'url-loader',
					options: {
						limit: 10240,
						name: 'images/[name]_[hash:8].[ext]',
					},
				}],
			},
			{
				test: /\.(woff|woff2|eot|ttf|otf)$/,
				use: [{
					loader: 'file-loader',
					options: {
						name: 'fonts/[name]_[hash:8].[ext]',
					},
				}],
			},
		],
	},
	plugins: [
		new CleanWebpackPlugin(),
		new MiniCssExtractPlugin({
			filename: 'css/[name]_[contenthash:8].css',
		}),
		new FriendlyErrorsWebpackPlugin(),
		// 错误捕获
		function () {
			this.hooks.done.tap('done', (stats) => {
				if (stats.compilation.errors && process.argv.indexOf('--watch') === -1) {
					process.exit(1);
				}
			});
		},
	].concat(HtmlWebpackPlugins),
	stats: 'errors-only',
};
